using System.Windows.Input;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Keyboard = Microsoft.Xna.Framework.Input.Keyboard;

namespace Silverlight3dApp.Learning.Lesson10
{
    public class MadnessGame : Game
    {
        private Camera _camera;
        private ModelManager _modelManager;

        public Camera Camera
        {
            get
            {
                return _camera;
            }
        }

        private float _shotSpeed = 20;
        private int _shotDelay = 300;
        private int _shotCountdown;

        private SpriteBatch _spriteBatch;
        private Texture2D _crosshairTexture;

        protected void FireShots(GameTime gameTime)
        {
            if (_shotCountdown <= 0)
            {
                var keyboardState = Keyboard.GetState();
                if (keyboardState.IsKeyDown(Key.Space))
                {
                    _modelManager.AddShot(_camera.CameraPosition + new Vector3(0, -5, 0), _camera.CameraDirection*_shotSpeed);
                    _shotCountdown = _shotDelay;
                }
            }
            else
            {
                _shotCountdown -= gameTime.ElapsedGameTime.Milliseconds;
            }
        }

        protected override void Initialize()
        {
            _camera = new Camera(this, new Vector3(0, 0, 50), new Vector3(0, 0, 0), Vector3.Up);
            Components.Add(_camera);
            _modelManager = new ModelManager(this);
            Components.Add(_modelManager);
            _spriteBatch = new SpriteBatch(GraphicsDevice);
            base.Initialize();
        }

        protected override void LoadContent()
        {
            _crosshairTexture = Content.Load<Texture2D>(@"Textures/Crosshair");
            base.LoadContent();
        }

        protected override void UnloadContent()
        {
            base.UnloadContent();
        }

        protected override void Update(GameTime gameTime)
        {
            FireShots(gameTime);
            base.Update(gameTime);
        }

        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Colors.Black, 1.0f, 0);
            base.Draw(gameTime);
            _spriteBatch.Begin();
            _spriteBatch.Draw(_crosshairTexture, new Vector2((float) GraphicsDevice.Viewport.Width/2 - (float) _crosshairTexture.Width/2, (float) GraphicsDevice.Viewport.Height/2 - (float) _crosshairTexture.Height/2), null, Color.White, 0, Vector2.Zero, 1.0f, SpriteEffects.None, 0);
            _spriteBatch.End();
        }
    }
}